﻿using banyuetan_2_0.IRepository.UnitOfWork;
using banyuetan_2_0.Model;
using banyuetan_2_0.Model.Models;
using banyuetan_2_0.Repository.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace banyuetan_2_0.Repository
{
    public class ArticleRepository : BaseRepository<Article>, IArticleRepository
    {
        public ArticleRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }

        public async override Task<Article> QueryById(object objId)
        {
            return await base.Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                //.WhereIF(c=>c.Sources.Any(),c=>c.Sources)
                //.Where(c => c.Sources.Any())
                //.Where(c => c.cIsDeleted == false)
                .In(Int32.Parse(objId.ToString()))
                .SingleAsync();
        }

        public async override Task<Article> QueryById(object objId, bool blnUseCache = false)
        {
            return await base.Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)//如果source为空，则会报sql参数为空格式错误，解决办法为
                //.Where(c => c.cIsDeleted == false)
                .WithCacheIF(blnUseCache)
                .In(Int32.Parse(objId.ToString()))
                .SingleAsync();
        }

        public async override Task<List<Article>> QueryByIDs(object[] lstIds)
        {
            return await base.Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                //.Where(c => c.cIsDeleted == false)
                .In(lstIds)
                .ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询所有数据
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query()
        {
            return await base.Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                //.Where(c => c.cIsDeleted == false)
                .ToListAsync();
        }


        /// <summary>
        /// 功能描述:查询数据列表
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query(string strWhere)
        {
            //return await Task.Run(() => Db.Queryable<Article>().WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToList());
            return await Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .WhereIF(!string.IsNullOrEmpty(strWhere), strWhere)
                .ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询数据列表
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <param name="whereExpression">whereExpression</param>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query(Expression<Func<Article, bool>> whereExpression)
        {
            return await Db.Queryable<Article>()
                .WhereIF(whereExpression != null, whereExpression)
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .ToListAsync();
        }

        /// <summary>
        /// 功能描述:按照特定列查询数据列表
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        public override async Task<List<TResult>> Query<TResult>(Expression<Func<Article, TResult>> expression)
        {
            return await Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .Select(expression)
                .ToListAsync();
        }

        /// <summary>
        /// 功能描述:按照特定列查询数据列表带条件排序
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="whereExpression">过滤条件</param>
        /// <param name="expression">查询实体条件</param>
        /// <param name="strOrderByFileds">排序条件</param>
        /// <returns></returns>
        public override async Task<List<TResult>> Query<TResult>(Expression<Func<Article, TResult>> expression, Expression<Func<Article, bool>> whereExpression, string strOrderByFileds)
        {
            return await Db.Queryable<Article>()
                .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).
                WhereIF(whereExpression != null, whereExpression)
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .Select(expression).ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询一个列表
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query(Expression<Func<Article, bool>> whereExpression, string strOrderByFileds)
        {
            //return await Task.Run(() => Db.Queryable<Article>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).ToList());
            return await Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .WhereIF(whereExpression != null, whereExpression)
                .OrderByIF(strOrderByFileds != null, strOrderByFileds)
                .ToListAsync();
        }
        /// <summary>
        /// 功能描述:查询一个列表
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="orderByExpression"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public override async Task<List<Article>> Query(Expression<Func<Article, bool>> whereExpression, Expression<Func<Article, object>> orderByExpression, bool isAsc = true)
        {
            //return await Task.Run(() => Db.Queryable<Article>().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToList());
            return await Db.Queryable<Article>()
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc)
                .WhereIF(whereExpression != null, whereExpression)
                .ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询一个列表
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query(string strWhere, string strOrderByFileds)
        {
            //return await Task.Run(() => Db.Queryable<Article>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToList());
            return await Db.Queryable<Article>()
                .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .WhereIF(!string.IsNullOrEmpty(strWhere), strWhere)
                .ToListAsync();
        }


        /// <summary>
        /// 功能描述:查询前N条数据
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intTop">前N条</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query(
            Expression<Func<Article, bool>> whereExpression,
            int intTop,
            string strOrderByFileds)
        {
            //return await Task.Run(() => Db.Queryable<Article>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).Take(intTop).ToList());
            return await Db.Queryable<Article>()
                .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c => c.Sources)
                .WhereIF(whereExpression != null, whereExpression)
                .Take(intTop)
                .ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询前N条数据
        /// 作　　者:banyuetan_2_0
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="intTop">前N条</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public override async Task<List<Article>> Query(
            string strWhere,
            int intTop,
            string strOrderByFileds)
        {
            //return await Task.Run(() => Db.Queryable<Article>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).Take(intTop).ToList());
            return await Db.Queryable<Article>()
                .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                .Includes(c => c.aTitlePic)
                .Includes(c => c.aEditor)
                .Includes(c=>c.Sources)
                .WhereIF(!string.IsNullOrEmpty(strWhere), strWhere)
                .Take(intTop)
                .ToListAsync();
        }

        /// <summary>
        /// 分页查询[使用版本，其他分页未测试]
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intPageIndex">页码（下标0）</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns></returns>
        public override async Task<PageModel<Article>> QueryPage(Expression<Func<Article, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null)
        {

            RefAsync<int> totalCount = 0;
            var list = await Db.Queryable<Article>()
             .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
             .Includes(c => c.aTitlePic)
             .Includes(c => c.aEditor)
             .Includes(c => c.Sources)
             .WhereIF(whereExpression != null, whereExpression)
             .ToPageListAsync(intPageIndex, intPageSize, totalCount);

            int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / intPageSize.ObjToDecimal())).ObjToInt();
            return new PageModel<Article>() { dataCount = totalCount, pageCount = pageCount, page = intPageIndex, PageSize = intPageSize, data = list };
        }
    }
}
